package com.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.BaseControllers;
import com.common.Criteria;
import com.common.GridReturn;
import com.common.MsgReturn;
import com.dao.XiaocaiArticleTypeMapper;
import com.google.gson.JsonObject;
import com.model.XiaocaiAdmin;
import com.model.XiaocaiArticle;
import com.model.XiaocaiArticleType;
import com.model.XiaocaiInput;
import com.model.XiaocaiUrls;
import com.model.XiaocaiUser;
import com.model.XiaocaiUserLog;
import com.model.XiaocaiWebConfig;
import com.service.UserService;
import com.service.WebConfigInfoService;
import com.service.XiaocaiAdminService;
import com.service.XiaocaiArticleService;
import com.service.XiaocaiArticleTypeService;
import com.service.XiaocaiInputService;
import com.service.XiaocaiUrlsService;
import com.service.XiaocaiUserLogService;
import com.service.XiaocaiUserService;
import com.util.JSONUtil;
import com.util.SessionUtils;
import com.util.StringUtil;
import com.util.WebConstants;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseControllers {

	@Resource
	private UserService userService;
	@Resource
	private XiaocaiUrlsService xiaocaiUrlsService;
	@Resource
	private XiaocaiUserService xiaocaiUserService;
	@Resource
	private XiaocaiInputService xiaocaiInputService;
	@Resource
	private XiaocaiArticleTypeService xiaocaiArticleTypeService;
	@Resource
	private XiaocaiArticleService xiaocaiArticleService;
	@Resource
	private WebConfigInfoService webConfigInfoService;
	@Resource
	private XiaocaiUserLogService xiaocaiUserLogService;
	
	@RequestMapping({ "", "/" })
	public ModelAndView index(ModelMap model,HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> context = new HashMap<String, Object>();
		//读取配置文件信息
		XiaocaiWebConfig xiaocaiWebConfig=webConfigInfoService.getXiaocaiWebConfig();
		context.put("xiaocaiWebConfig", xiaocaiWebConfig);
		return forword("/admin/index", context);
	}

	@RequestMapping(value = "/index")
	public ModelAndView main(ModelMap model) {
		Map<String, Object> context = new HashMap<String, Object>();
		//读取配置文件信息
		XiaocaiWebConfig xiaocaiWebConfig=webConfigInfoService.getXiaocaiWebConfig();
		context.put("xiaocaiWebConfig", xiaocaiWebConfig);
		return forword("/admin/index", context);
	}
	@RequestMapping(value = "makeConfig.json")
	@ResponseBody
	public void makeWebConfig(XiaocaiWebConfig xiaocaiWebConfig,HttpServletResponse response) {
		try {
			boolean result=webConfigInfoService.setXiaocaiWebConfig(xiaocaiWebConfig);
			if(result){
				writerJson(response, successMsg("审核成功"));}
			else {
				writerJson(response, errorMsg("审核失败"));
			}
		} catch (Exception e) {
			writerJson(response, errorMsg("审核失败"));
		}
		
	}
	/**
	 * 会员管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user")
	public ModelAndView index() {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("admin/user", context);
	}

	/**
	 * 会员列表
	 * 
	 * @param criteria
	 * @param response
	 */
	@RequestMapping(value = "/user_list.json")
	public void list(Criteria criteria, HttpServletResponse response) {
		int total = xiaocaiUserService.getTotal(criteria);
		criteria.setRowCount(total);
		List list = xiaocaiUserService.selectByCriteriaPagination(criteria);
		writerJson(response, new GridReturn(total, list).toString());
	}

	@RequestMapping(value = "/add_point_update_user.json")
	public void addPointToUser(XiaocaiUser xiaocaiUser,
			HttpServletResponse response) {
		try {
			/*System.out.println("用户充值");
			System.out.println("用户ID" + xiaocaiUser.getId());
			System.out.println("充入积分数" + xiaocaiUser.getUserPoint());
			System.out.println("充入金额" + xiaocaiUser.getUserMoney());*/
			xiaocaiUserService.addPoint(xiaocaiUser.getId(), xiaocaiUser.getUserPoint());
			xiaocaiUserService.addMoney(xiaocaiUser.getId(), xiaocaiUser.getUserMoney());
			if(xiaocaiUser.getUserMoney()!=0)
				xiaocaiUserLogService.addXiaocaiUserLogService(xiaocaiUser.getId(),XiaocaiUserLog.ADMIN_INPUT_MONEY,"管理员充值"+ xiaocaiUser.getUserMoney()+"元");
			if(xiaocaiUser.getUserPoint()!=0)
				xiaocaiUserLogService.addXiaocaiUserLogService(xiaocaiUser.getId(),XiaocaiUserLog.ADMIN_INPUT_POINT,"管理员充积分"+ xiaocaiUser.getUserPoint()+"个");
			
			
			writerJson(response, successMsg("充值成功"));
		} catch (Exception e) {
			writerJson(response, errorMsg("充值失败"));
		}
	}

	@RequestMapping(value = "/input_list")
	public ModelAndView inputList() {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("admin/input_list", context);
	}

	@RequestMapping(value = "/input_list.json")
	public void inputListForJson(Criteria criteria, HttpServletResponse response) {
		int total = xiaocaiInputService.getTotal(criteria);
		criteria.setRowCount(total);
		List<XiaocaiInput> list = xiaocaiInputService.selectByCriteriaPagination(criteria);
		writerJson(response, new GridReturn(total, list).toString());
	}
	@RequestMapping(value = "/deal_input_for_user.json")
	public void dealInputForUser(int isPass,XiaocaiInput xiaocaiInput, HttpServletResponse response) {
		XiaocaiInput xiaocaiInputOld=xiaocaiInputService.selectByPrimaryKey(xiaocaiInput.getId());
		if(xiaocaiInputOld.getInputStatus()!=0){
			//已经审核过了，不能再审核
			writerJson(response, errorMsg("已经审核过了，不能再审核"));
			return;
		}
		if (isPass==0) {
			xiaocaiInputOld.setInputStatus(-1);
		}else {
			xiaocaiInputOld.setInputStatus(1);
		}
		xiaocaiInputOld.setInputPassDate(new Date());
		int result=xiaocaiInputService.updateXiaocaiInputService(xiaocaiInputOld);
		if (result>0) {
			//更新用户金额
			XiaocaiUser xiaocaiUser=xiaocaiUserService.selectByPrimaryKey(xiaocaiInputOld.getUserIdP());
			if (xiaocaiInputOld.getInputType()==1) {
				//审核通过
				if(xiaocaiInputOld.getInputStatus()==1){
					//用户提现
					xiaocaiUser.setFrozenMoney(xiaocaiUser.getFrozenMoney()-xiaocaiInputOld.getInputMoney());
					xiaocaiUserLogService.addXiaocaiUserLogService(xiaocaiUser.getId(),XiaocaiUserLog.ADMIN_PAYOUT_PASS,"管理员提现通过"+ xiaocaiInputOld.getInputMoney()+"元");
					
				}else{
					//冻结金额退回
					xiaocaiUser.setFrozenMoney(xiaocaiUser.getFrozenMoney()-xiaocaiInputOld.getInputMoney());
					xiaocaiUser.setUserMoney(xiaocaiUser.getUserMoney()+xiaocaiInputOld.getInputMoney());
					xiaocaiUserLogService.addXiaocaiUserLogService(xiaocaiUser.getId(),XiaocaiUserLog.ADMIN_PAYOUT_NO_PASS,"管理员提现不通过，退回"+ xiaocaiInputOld.getInputMoney()+"元");
					
				}
			}else {
				//用户充值
				if(xiaocaiInputOld.getInputStatus()==1){
					xiaocaiUser.setUserMoney(xiaocaiUser.getUserMoney()+xiaocaiInputOld.getInputMoney());
					xiaocaiUserLogService.addXiaocaiUserLogService(xiaocaiUser.getId(),XiaocaiUserLog.ADMIN_PAYIN_PASS,"管理员充值通过"+ xiaocaiInputOld.getInputMoney()+"元");
					
				}else {
					//充值审核不通过，不做任何操作
				}
			}
			xiaocaiUserService.updateByPrimaryKey(xiaocaiUser);
			writerJson(response, successMsg("处理成功"));
		}else {
			writerJson(response, errorMsg("处理失败"));
		}
	}
	

	/**
	 * 网址管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/urls")
	public ModelAndView urls() {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("admin/urls", context);
	}

	/**
	 * 网址列表
	 * 
	 * @param criteria
	 * @param response
	 */
	@RequestMapping(value = "/urls_list.json")
	public void urlsList(Criteria criteria, HttpServletResponse response) {

		int total = xiaocaiUrlsService.getTotal(criteria);
		criteria.setRowCount(total);
		criteria.setOrder("url_id");
		List list = xiaocaiUrlsService.selectByCriteriaPagination(criteria);
		writerJson(response, new GridReturn(total, list).toString());
	}

	@RequestMapping(value = "/url_delete.json")
	public void urlsDelete(String ids, HttpServletResponse response) {
		int[] idsArray = StringUtil.stringToIntArray(ids);
		xiaocaiUrlsService.deleteBatch(idsArray);
		writerJson(response, successMsg("删除成功"));
	}

	@RequestMapping(value = "/url_pass.json")
	public void urlsPass(String ids, HttpServletResponse response) {
		try {
			int[] idsArray = StringUtil.stringToIntArray(ids);
			xiaocaiUrlsService.passBatch(idsArray);
			writerJson(response, successMsg("审核成功"));
		} catch (Exception e) {
			writerJson(response, errorMsg("审核失败"));
		}
	}

	/**
	 * 文章类型管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/article_type_list")
	public ModelAndView articleTypeList() {
		Map<String, Object> context = new HashMap<String, Object>();
		return forword("admin/list_article_type", context);
	}

	/**
	 * 文章类型列表
	 * 
	 * @param criteria
	 * @param response
	 */
	@RequestMapping(value = "/list_article_type.json")
	public void listArticleTypeJson(Criteria criteria,
			HttpServletResponse response) {
		int total = xiaocaiArticleTypeService.getTotal(criteria);
		criteria.setRowCount(total);
		List list = xiaocaiArticleTypeService
				.selectByCriteriaPagination(criteria);
		writerJson(response, new GridReturn(total, list).toString());
	}

	@RequestMapping(value = "/add_article_type.json")
	public void addArticleTypeJson(XiaocaiArticleType xiaocaiArticleType,
			HttpServletResponse response) {
		xiaocaiArticleTypeService.addxiaocaiInputService(xiaocaiArticleType);
		writerJson(response, successMsg("新增成功"));
	}

	@RequestMapping(value = "/edit_article_type.json")
	public void editArticleTypeJson(XiaocaiArticleType xiaocaiArticleType,
			HttpServletResponse response) {
		xiaocaiArticleTypeService.editxiaocaiInputService(xiaocaiArticleType);
		writerJson(response, successMsg("修改成功"));
	}

	@RequestMapping(value = "/delete_article_type.json")
	public void deleteArticleType(String ids, HttpServletResponse response) {
		int[] idsArray = StringUtil.stringToIntArray(ids);
		xiaocaiArticleTypeService.deleteBatch(idsArray);
		writerJson(response, successMsg("删除成功"));
	}

	/**
	 * 文章管理
	 * 
	 * @return
	 */
	@RequestMapping(value = "/article_list")
	public ModelAndView articleList() {
		Map<String, Object> context = new HashMap<String, Object>();
		//获取文章类型
		Criteria criteria=new Criteria();
		List<XiaocaiArticleType> list = xiaocaiArticleTypeService.selectByCriteriaPagination(criteria);
		context.put("typeList", list);
		return forword("admin/list_article", context);
	}

	/**
	 * 文章列表
	 * 
	 * @param criteria
	 * @param response
	 */
	@RequestMapping(value = "/list_article.json")
	public void listArticleJson(Criteria criteria, HttpServletResponse response) {
		int total = xiaocaiArticleService.getTotal(criteria);
		criteria.setRowCount(total);
		List list = xiaocaiArticleService.selectByCriteriaPagination(criteria);
		writerJson(response, new GridReturn(total, list).toString());
	}
	@RequestMapping(value = "/get_article.json")
	public void getArticleJson(int id,
			HttpServletResponse response) {
		XiaocaiArticle xiaocaiArticle=xiaocaiArticleService.selectByPrimaryKey(id);
		writerJson(response,xiaocaiArticle);
	}
	
	@RequestMapping(value = "/add_article.json")
	public void addArticleJson(XiaocaiArticle xiaocaiArticle,
			HttpServletResponse response) {
		xiaocaiArticle.setArticleCreateDate(new Date());
		xiaocaiArticleService.addXiaocaiArticle(xiaocaiArticle);
		writerJson(response, successMsg("新增成功"));
	}

	@RequestMapping(value = "/edit_article.json")
	public void editArticleJson(XiaocaiArticle xiaocaiArticle,
			HttpServletResponse response) {
		xiaocaiArticle.setArticleCreateDate(new Date());
		xiaocaiArticleService.editXiaocaiArticle(xiaocaiArticle);
		writerJson(response, successMsg("修改成功"));
	}

	@RequestMapping(value = "/delete_article.json")
	public void deleteArticle(String ids, HttpServletResponse response) {
		int[] idsArray = StringUtil.stringToIntArray(ids);
		xiaocaiArticleService.deleteBatch(idsArray);
		writerJson(response, successMsg("删除成功"));
	}

	@RequestMapping(value = "/upload_json.json")
	public void uploadFileJson(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			ServletContext application = request.getSession()
					.getServletContext();
			String savePath = application.getRealPath("/") + "resources/attached/";

			// 文件保存目录URL
			String saveUrl = request.getContextPath() + "/resources/attached/";

			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			extMap.put("flash", "swf,flv");
			extMap.put("media",
					"swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			extMap.put("file",
					"doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

			// 最大文件大小
			long maxSize = 1000000;

			response.setContentType("text/plain;charset=UTF-8");

			if (!ServletFileUpload.isMultipartContent(request)) {
				writerJson(response, errorMsg2("请选择文件"));
				return;
			}
			// 检查目录
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				writerJson(response, errorMsg2("上传目录不存在"));
				return;
			}
			// 检查目录写权限
			if (!uploadDir.canWrite()) {
				writerJson(response, errorMsg2("上传目录没有写权限"));
				return;
			}

			String dirName = request.getParameter("dir");
			if (dirName == null) {
				dirName = "image";
			}
			if (!extMap.containsKey(dirName)) {
				writerJson(response, errorMsg2("目录名不正确"));
				return;
			}
			// 创建文件夹
			savePath += dirName + "/";
			saveUrl += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			saveUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List items;
			items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String fileName = item.getName();
				if (!item.isFormField()) {
					// 检查文件大小
					if (item.getSize() > maxSize) {
						writerJson(response, errorMsg2("上传文件大小超过限制"));
						return;
					}
					// 检查扩展名
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					if (!Arrays.<String> asList(extMap.get(dirName).split(","))
							.contains(fileExt)) {
						writerJson(response, errorMsg2("上传文件扩展名是不允许的扩展名。\n只允许"
								+ extMap.get(dirName) + "格式。"));
						return;
					}

					SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
					String newFileName = df.format(new Date()) + "_"
							+ new Random().nextInt(1000) + "." + fileExt;
					File uploadedFile = new File(savePath, newFileName);
					item.write(uploadedFile);
					Map<String, Object> msg = new HashMap<String, Object>();
					msg.put("error", 0);
					msg.put("url", saveUrl + newFileName);
					writerJson(response, msg);
					return;
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return;
	}
	private String errorMsg2(String msg){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("error", 1);
		obj.put("msg", msg);
		return JSONUtil.toJson(obj);
	}
}
